package com.example.test02;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.test02.adapter.NewsAdapter;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class NewsFragment extends Fragment {

    private String[] titles;
    private String[] descriptions;
    private String[] dates;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_news, container, false);

        ListView listView = view.findViewById(R.id.listView);

        // 获取缓存的 userId
        Integer userId = getUserIdFromCache();

        if (userId != null) {
            // 发送请求获取消息信息
            getNewsInfo(userId);
        } else {
            // 用户未登录或 userId 未缓存
            Toast.makeText(getContext(), "用户未登录或 userId 未缓存", Toast.LENGTH_SHORT).show();
        }

        return view;
    }

    private void getNewsInfo(int userId) {
        OkHttpClient client = new OkHttpClient();
        String userIdString = String.valueOf(userId);

        Request request = new Request.Builder()
                .url("http://120.26.59.7:17321/api/messages?userId=" + userIdString)
                .get()
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                requireActivity().runOnUiThread(() -> {
                    Toast.makeText(getContext(), "网络请求失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) {
                    requireActivity().runOnUiThread(() -> {
                        Toast.makeText(getContext(), "服务器返回错误: " + response.code(), Toast.LENGTH_SHORT).show();
                    });
                    return;
                }

                String responseData = response.body().string();
                try {
                    JSONObject jsonResponse = new JSONObject(responseData);
                    int code = jsonResponse.getInt("code");
                    String message = jsonResponse.getString("message");

                    if (code == 0) {
                        JSONArray data = jsonResponse.getJSONArray("data");

                        List<String> titlesList = new ArrayList<>();
                        List<String> descriptionsList = new ArrayList<>();
                        List<String> datesList = new ArrayList<>();

                        for (int i = 0; i < data.length(); i++) {
                            JSONObject news = data.getJSONObject(i);
                            titlesList.add(news.getString("messageContent"));
                            descriptionsList.add(news.getString("messageContent"));
                            datesList.add(news.getString("sendDate"));
                        }

                        requireActivity().runOnUiThread(() -> {
                            // 更新 UI
                            titles = titlesList.toArray(new String[0]);
                            descriptions = descriptionsList.toArray(new String[0]);
                            dates = datesList.toArray(new String[0]);

                            ListView listView = getView().findViewById(R.id.listView);
                            listView.setAdapter(new NewsAdapter(getContext(), titles, descriptions, dates));
                        });
                    } else {
                        requireActivity().runOnUiThread(() -> {
                            Toast.makeText(getContext(), "获取消息信息失败: " + message, Toast.LENGTH_SHORT).show();
                        });
                    }
                } catch (Exception e) {
                    requireActivity().runOnUiThread(() -> {
                        Toast.makeText(getContext(), "解析响应数据失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                    });
                }
            }
        });
    }

    private int getUserIdFromCache() {
        SharedPreferences sharedPreferences = requireActivity().getSharedPreferences("UserPrefs", Context.MODE_PRIVATE);
        return sharedPreferences.getInt("userId", -1);
    }
}

